package ishangchao.cn.haliaeetus.schedules

import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import com.kalemao.library.base.MResponse
import com.kalemao.library.custom.recycler_headandfoot.HeaderAndFooterAdapter
import com.kalemao.library.custom.stateful.StatefulLayout
import com.kalemao.library.http.BaseObserver
import com.kalemao.library.http.JsonUtils
import com.kalemao.library.refresh.SuperSwipeRefreshLayout
import ishangchao.cn.haliaeetus.BR
import ishangchao.cn.haliaeetus.R
import ishangchao.cn.haliaeetus.base.CommonItemViewHolder
import ishangchao.cn.haliaeetus.base.CommonItemViewHolder.OnViewClickListener
import ishangchao.cn.haliaeetus.base.CommonRecyclerViewAdapter
import ishangchao.cn.haliaeetus.base.HaliaeetusFragment
import ishangchao.cn.haliaeetus.databinding.SchedulesFragmentBinding
import ishangchao.cn.haliaeetus.http.HttpNetWork
import ishangchao.cn.haliaeetus.schedules.model.MSchedulesAll
import ishangchao.cn.haliaeetus.schedules.model.MSchedulesBean
import org.jetbrains.anko.support.v4.toast
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

/**
 * Created by junlihou on 2018/6/6.
 */
class SchedulesFragment : HaliaeetusFragment(), SuperSwipeRefreshLayout.OnPullRefreshListener, SuperSwipeRefreshLayout.OnPushLoadMoreListener {
    lateinit var mBinding: SchedulesFragmentBinding

    private var doesFirst = true

    private var mSchedulesAll: MSchedulesAll? = null
    private var mSchedulesList = ArrayList<MSchedulesBean>()
    private var mAdapter: CommonRecyclerViewAdapter<MSchedulesBean>? = null
    lateinit var mHeader: HeaderAndFooterAdapter<ViewHolder>

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
    }

    override fun beforeInit() {
        super.beforeInit()
        doesUseDataBanding = true
    }

    override fun setStatefulLayout(): StatefulLayout? {
        if (!doesFirst && mBinding != null) {
            return mBinding.fraTravleStateful
        }
        return null
    }

    override fun getLayoutId(): Int {
        return R.layout.schedules_fragment
    }

    override fun initData() {
        mBinding.fraTravleRefresh.setOnPushLoadMoreListener(this)
        mBinding.fraTravleRefresh.setOnPullRefreshListener(this)
        getList(1)
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBinding = mDataBanding as SchedulesFragmentBinding
        doesFirst = false

    }

    private fun getList(page: Int) {
        showLoading()
        HttpNetWork.getInstance().haliaeetusApi.getSchedules(page, 10).subscribeOn(Schedulers.io()).observeOn(
                AndroidSchedulers.mainThread()).subscribe(object : BaseObserver<MResponse>() {
            override fun onError(e: Throwable) {
                super.onError(e)
                resetRefresh()
                closeLoading()
            }

            override fun onNext(mResponse: MResponse) {
                if (mResponse.doesSuccess()) {
                    mSchedulesAll = JsonUtils.fromJsonDate(mResponse.data, MSchedulesAll::class.java)
                    initDataBack()
                } else {
                    toast(mResponse.biz_msg)
                }
                closeLoading()
                resetRefresh()
            }
        })
    }

    /**
     * 数据返回处理
     *
     * @author dim.
     * @time 2018/6/15 16:18.
     */
    private fun initDataBack() {
        if (mSchedulesAll == null) {
            return
        }
        if (mSchedulesList == null) {
            mSchedulesList = ArrayList()
        }
        if (mSchedulesAll!!.current_page == 1) {
            mSchedulesList.clear()
        }
        mSchedulesList.addAll(mSchedulesAll!!.schedules)

        if (mSchedulesList.size == 0) {
            showEmpty("", "暂无数据")
            return
        } else {
            showContent()
        }
        if (mAdapter == null) {
            val llm = LinearLayoutManager(activity)
            mBinding.fraTravleRecycler.layoutManager = llm
            mBinding.fraTravleRecycler.setHasFixedSize(true)
            val variableId = BR.scheduledBean
            mAdapter = object : CommonRecyclerViewAdapter<MSchedulesBean>(R.layout.item_schedules, variableId,
                    mSchedulesList
            ) {
                override fun convert(holder: CommonItemViewHolder, position: Int, bean: MSchedulesBean) {
                    holder.setBindingWithClick(variableId, bean, object : OnViewClickListener {
                        override fun onViewClick(detailID: String) {
                            var intent = Intent()
                            intent.setClass(activity,SchedulesDetailsActivity::class.java)
                            intent.putExtra("id",detailID)
                            activity!!.startActivity(intent)
                        }
                    })
                }
            }

            mHeader = HeaderAndFooterAdapter(mAdapter)
            mBinding.fraTravleRecycler.adapter = mHeader
        } else {
            mAdapter!!.setDatas(mSchedulesList)
            mHeader.notifyDataSetChanged()
        }

        if (mSchedulesAll!!.current_page * mSchedulesAll!!.per_page < mSchedulesAll!!.total) {
            mBinding.fraTravleRefresh.setOnPushLoadMoreListener(this)
            removeFootViewForRecycler(mHeader)
        } else {
            addFootEmptyView(mHeader)
            mBinding.fraTravleRefresh.setOnPushLoadMoreListener(null)
        }
    }

    /**
     * 刷新或者加载更多回来时候需要关闭
     *
     * @author dim.
     * @time 2018/6/15 14:54.
     */
    private fun resetRefresh() {
        closeLoading()
        if (mBinding.fraTravleRefresh.isRefreshing) {
            mBinding.fraTravleRefresh.isRefreshing = false
        }
        if (mBinding.fraTravleRefresh.isLoadMore) {
            mBinding.fraTravleRefresh.isLoadMore = false
        }
    }

    override fun onLoadMore() {
        getList(mSchedulesAll!!.current_page + 1)
    }

    override fun onLoadMorePushDistance(distance: Int) {

    }

    override fun onLoadMorePushEnable(enable: Boolean) {

    }

    override fun onRefresh() {
        getList(1)
    }

    override fun onRefreshPullDistance(distance: Int) {

    }

    override fun onRefreshPullEnable(enable: Boolean) {

    }
}